from src.repo import deployment_repo
from src.common.tool import root_path
from src.common import shell
import uuid

script_create_branch = f'{root_path}/scripts/git-create-branch.sh'
script_latest_commit = f'{root_path}/scripts/git-latest-commit.sh'
script_merge = f'{root_path}/scripts/git-merge.sh'
script_init = f'{root_path}/scripts/git-init.sh'


def create_deployment_branch(project_id, environment_id) -> str:
    """

    :param project_id: project id
    :param environment_id: environment_id
    :return: 分支名称
    """
    project = deployment_repo.query_project_by_id(project_id)
    env = deployment_repo.query_env_by_id(environment_id)
    new_branch_name = f"release_{env.name}_{str(uuid.uuid4()).replace('-', '')}"
    shell.execute_script(script_create_branch, [project.local_folder, new_branch_name])
    return new_branch_name


def create_feature_branch(project_id, feature_id) -> str:
    """

    :param project_id: 项目ID
    :param feature_id: 需求ID
    :return: 分支名称
    """
    project = deployment_repo.query_project_by_id(project_id)
    new_branch_name = f"feature_{project_id}_{feature_id}_{str(uuid.uuid4()).replace('-', '')}"
    shell.execute_script(script_create_branch, [project.local_folder, new_branch_name])
    return new_branch_name


def get_latest_commit(folder, branch_name):
    return shell.execute_script(script_latest_commit, [folder, branch_name])


def do_merge_branch(folder, merge_branch, feature_branch) -> str:
    # 返回 feature_branch_id 最新的提交
    shell.execute_script_with_output(script_merge, [folder, merge_branch, feature_branch])
    return get_latest_commit(folder, feature_branch)
